package com.examination.auth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.examination.auth.mapper.UserMapper;
import com.examination.auth.service.ClassInfoService;
import com.examination.auth.service.UserService;
import com.examination.auth.utils.JwtUtil;
import com.examination.auth.utils.RedisCache;
import com.examination.auth.utils.SecurityUtil;
import com.examination.constants.SystemConstants;
import com.examination.domain.auth.entity.LoginUser;
import com.examination.domain.auth.entity.User;
import com.examination.domain.auth.vo.LoginUserVo;
import com.examination.domain.auth.vo.UserInfoVo;
import com.examination.domain.common.ResponseResult;
import com.examination.domain.utils.BeanCopyUtils;
import com.examination.enums.AppHttpCodeEnum;
import com.examination.exception.MySystemException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private ClassInfoService classInfoService;


    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //校验是否认证通过
        if (Objects.isNull(authenticate)) {
            throw new MySystemException(AppHttpCodeEnum.LOGIN_ERROR);
        }

        //获取userId并生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String id = loginUser.getUser().getSid().toString();
        String jwt = JwtUtil.createJwt(id);

        //把用户信息存入redis
        redisCache.setCacheObject(SystemConstants.REDIS_PRE + id, loginUser);

        //把token和userInfo封装成ResponseResult返回
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);

        return ResponseResult.okResult(new LoginUserVo(jwt, setUserInfo(userInfoVo, loginUser.getUser())));
    }


    private UserInfoVo setUserInfo(UserInfoVo userInfoVo, User user) {
        switch (user.getSex()) {
            case "0":
                userInfoVo.setSex(SystemConstants.USER_GENDER_MALE);
                break;
            case "1":
                userInfoVo.setSex(SystemConstants.USER_GENDER_FEMALE);
                break;
            case "2":
                userInfoVo.setSex(SystemConstants.USER_GENDER_IGNORANT);
                break;
            default:
                log.info("用户性别为空！");
        }
        log.info("userInfoVo:{}", userInfoVo.toString());
        if (user.getType() == null) {
            throw new MySystemException(AppHttpCodeEnum.TYPE_NOT_NULL);
        }
        switch (user.getType()) {
            case "0":
                userInfoVo.setTypeName(SystemConstants.USER_TYPE_STUDENT);
                break;
            case "1":
                userInfoVo.setTypeName(SystemConstants.USER_TYPE_TEACHER);
                break;
            default:
                log.info("用户类型为空！");
        }
        if (user.getCid()!=null){
            userInfoVo.setClassName(classInfoService.getById(user.getCid()).getClassName());
        }
        return userInfoVo;
    }


    @Override
    public ResponseResult register(User user) {
        //对数据进行非空判断
        if (!StringUtils.hasText(user.getUsername())) {
            throw new MySystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if (!StringUtils.hasText(user.getPassword())) {
            throw new MySystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }

        //对密码进行加密
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        //存入数据库
        save(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getUserInfo() {
        LoginUser loginUser = SecurityUtil.getLoginUser();
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        return ResponseResult.okResult(setUserInfo(userInfoVo,loginUser.getUser()));
    }
}
